<template>
    <view class="cu-modal bottom-modal" :class="{ show: visible }">
        <view class="mask" @click="close"></view>
        <view class="wrapper cu-dialog">
            <view class="relative">
                <view class="title">
                    {{ data.name }}
                    <view class="close" @click="close">
                        <text class="cuIcon-close"></text>
                    </view>
                </view>
            </view>
            <view>
                <view class="flex-align paddingY10">
                    <view class="flex1 font4">购买盒数</view>
                    <view class="color-theme">
                        <text class="font6">¥</text>
                        <text class="font6 marginR5">{{ data.price }} x {{ num }}</text>
                    </view>
                </view>
                <view class="flex-align paddingY10">
                    <view class="flex1 font4">优惠券</view>
                    <view class="font2 marginR5" :class="couponAmount ? 'color-theme' : ''">
                        {{ couponAmount ? '已使用优惠¥' : '' }}
                        {{ couponAmount || '暂无优惠券可选' }}
                    </view>
                </view>
                <view class="flex-align paddingY10" v-if="rockShow&&magic">
                    <view class="flex1 font4">
                        源石
                        <view class="blance">(剩余源石：{{ magic.balance || 0 }})</view>
                    </view>
                    <view class="font2 blance marginR5">
                        已抵扣
                        <span class="font6 color-theme">¥{{ coin || 0 }}</span>
                    </view>
                </view>
                <view v-if="cash && hide" class="flex-align paddingY10">
                    <view class="flex1 font4">
                        使用钱包支付
                        <text class="color-theme">(余额：¥{{ cash.balance }})</text>
                    </view>
                    <radio
                        color="#FF9600"
                        value="r1"
                        :checked="cashChecked"
                        style="transform: scale(0.7)"
                        @click.stop="changeCashChecked"
                    />
                </view>
                <view class="paddingY10 flex-align-between">
                    <view>
                        <view class="font3 flex-align" @click="showWeb">
                            我已满18周岁，已阅读并同意
                            <text style="color: #ff9600">《宝箱服务协议》</text>
                        </view>
                        <view class="font2 color-2 paddingY6">
                            宝箱商品存在概率性，请谨慎消费，未满18周岁禁止参与
                        </view>
                        <view class="color-2 font2 line-ellipsis">不支持7天无理由退换货</view>
                    </view>

                    <radio
                        color="#FF9600"
                        value="r1"
                        :checked="checked"
                        style="transform: scale(0.7)"
                        @click.stop="changeChecked"
                    />
                </view>
            </view>
            <view class="payBox">
                <view class="payPrice" v-if="lastPrice != null">
                    实付：
                    <span class="payNum">¥{{ lastPrice.toFixed(2) }}</span>
                </view>
                <button class="payBtn" style="" v-if="lastPrice != null" @click="pay()">
                    立即支付
                </button>
            </view>

            <view class="fill"></view>
        </view>
    </view>
</template>

<script>
    import cmButton from '../../components/cm-button.vue'
    import { throttle } from '@/utils'
    import { H5 } from '@/utils/config'
    import resource from '@/utils/resource'
    import { baseEncode } from '../../utils/utils'
    export default {
        components: { cmButton },
        props: {
            data: Object,
            poolId: Number
        },
        data() {
            return {
                resource,
                num: 1,
                visible: false,
                checked: true,
                coin: '',
                couponAmount: null,
                cash: null,
                cashChecked: false,
                lastPrice: null, //最终金额
                clickFlag: false,
                magic: null,
                bizTradeNo: ''
            }
        },
        computed: {
            hide() {
                return !this.$store.state.hide
            },
            payInfo() {
                return this.$store.state.payInfo
            },
			rockShow() {
										let val = false
										val = uni.getStorageSync('rockShow')
										return val
									}
        },
        watch: {
            payInfo(val) {
                if (val && val.payResult == 'SUCCESS') {
                    this.paySuccess(val)
                } else if (val && val.payResult !== 'SUCCESS') {
                }
            }
        },
        methods: {
            show(num, data = {}, boxNum, seatNumbers, packFlag) {
                this.num = num
                this.boxNum = boxNum
                this.seatNumbers = seatNumbers
                this.coin = data.magicAmount || null
                this.couponAmount = data.couponAmount || null
                this.lastPrice = data.paymentAmount
				this.magic = data.magic
                if (data.cash && data.cash.balance > data.paymentAmount) {
                    this.cash = data.cash
                    this.cashChecked = true
                } else {
                    this.cash = null
                    this.cashChecked = false
                }
                this.packFlag = packFlag || null
                this.visible = true
            },
            close() {
                this.visible = false
                this.$emit('close', false)
            },
            changeChecked(e) {
                this.checked = !this.checked
            },
            changeCashChecked(e) {
                this.cashChecked = !this.cashChecked
            },
            async pay() {
                if (this.clickFlag) return
                throttle.call(this.realPay)
            },
            async realPay() {
                if (!this.checked) {
                    this.$message.error('请同意《宝箱服务协议》')
                    return
                }
                let paymentType = this.cashChecked ? 'WALLET' : 'WXPAY_JSAPI'
                const res = await this.$service.award.apply(
                    this.poolId,
                    this.packFlag ? 1 : this.num,
                    paymentType,
                    this.boxNum,
                    this.seatNumbers,
                    this.packFlag
                )
                //判断是否是微信支付
                if (res) {
                    if (res.paySuccess) {
                        this.clickFlag = true
                        setTimeout(() => {
                            this.$emit('success', { tradeNo: res.bizTradeNo, num: this.num })
                        }, 50)
                        setTimeout(() => {
                            this.close()
                            this.clickFlag = false
                        }, 350)
                        return
                    }
                    if(res.redirectUrl){
                      this.thirdPay(res)
                    }else{
                      this.wechatPay(res)
                    }

                } else {
                    this.$event.emit(this.$event.key.NUM_REFRESH)
                }
            },
            encode(arraybuffer) {
                var bytes = new Uint8Array(arraybuffer),
                    i,
                    len = bytes.length,
                    base64 = ''
                for (i = 0; i < len; i += 3) {
                    base64 += chars[bytes[i] >> 2]
                    base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)]
                    base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)]
                    base64 += chars[bytes[i + 2] & 63]
                }
                if (len % 3 === 2) {
                    base64 = base64.substring(0, base64.length - 1) + '='
                } else if (len % 3 === 1) {
                    base64 = base64.substring(0, base64.length - 2) + '=='
                }
                return base64
            },
            wechatPay(data) {
                let payInfo = data.payInfo
                wx.requestPayment({
                    timeStamp: payInfo.timeStamp,
                    nonceStr: payInfo.nonceStr,
                    package: payInfo.packageValue,
                    signType: payInfo.signType,
                    paySign: payInfo.paySign,
                    success: (res) => {
                        this.clickFlag = true
                        setTimeout(() => {
                            this.$emit('success', { tradeNo: data.bizTradeNo, num: this.num })
                        }, 50)
                        setTimeout(() => {
                            this.close()
                            this.clickFlag = false
                        }, 350)
                    },
                    fail: (res) => {}
                })
            },
            thirdPay(data) {
                let self = this
                let redirectUrl = data.redirectUrl
                let requestId = data.requestId
                this.bizTradeNo = data.bizTradeNo
                const base64Url = encodeURIComponent(baseEncode(redirectUrl))
                wx.openEmbeddedMiniProgram({
                    path: 'pages/pay/order', // 启动目标页面
                    appId: 'wx0448557563ffc600', // 启动的小程序
                    envVersion: 'release', // develop | trial | release
                    verify: 'binding',
                    extraData: {
                        title: '购买' + `${self.data.name}X${self.num}`, // 导航Title
                        tip: `￥${self.data.price}(${self.data.name}X${self.num})`, // 支付提示内容
                        requestId: requestId, // 本次请求ID
                        action: 'epPay', // 支付模式
                        payUrl: base64Url // 支付地址, 需要进行Base64转换
                    },
                    success: (res) => {
                        console.info('启动成功', res)
                    },
                    fail: (err) => {
                        console.info('启动失败', err)
                    }
                })
            },
            paySuccess(payInfo) {
                this.clickFlag = true
                console.log(this.bizTradeNo)
                setTimeout(() => {
                    this.$emit('success', { tradeNo: this.bizTradeNo, num: this.num })
                }, 50)
                setTimeout(() => {
                    this.bizTradeNo = ''
                    this.$store.state.payInfo = null
                    this.close()
                    this.clickFlag = false
                }, 350)
            },
            showWeb() {
                this.$router.web(H5.moli.url, H5.moli.title)
            }
        }
    }
</script>

<style lang="scss" scoped>
    .mask {
        position: absolute;
        left: 0;
        right: 0;
        top: 0;
        bottom: 0;
    }
    .wrapper {
        padding: 0 28rpx;
        background: #fff;
        border-radius: 15px 15px 2px 2px !important;
        overflow: hidden;
        .title {
            text-align: center;
            font-size: 32rpx;
            font-family: Source Han Sans, Source Han Sans;
            font-weight: 700;
            color: #000000;
            padding: 44rpx 0 48rpx 0;
            position: relative;
        }
        .x {
            width: 32rpx;
            height: 32rpx;
        }
        .close {
            position: absolute;
            right: 0rpx;
            width: 48rpx;
            height: 48rpx;
            background: #ebebeb;
            border-radius: 48rpx;
            color: #a2a2a2;
            top: 30rpx;
            line-height: 48rpx;
        }
        .logo {
            width: 180rpx;
            height: 180rpx;
        }
        .fill {
            height: 50rpx;
        }
    }
    .blance {
        display: inline-block;
        font-size: 24rpx;
        font-family: Source Han Sans, Source Han Sans;
        font-weight: 350;
        color: #999999;
        margin-left: 10rpx;
    }
    .payBox {
        display: flex;
        width: 100%;
        justify-content: space-between;
        align-items: center;
        margin-top: 40rpx;
        .payPrice {
            font-size: 28rpx;
            font-family: Source Han Sans, Source Han Sans;
            font-weight: 350;
            color: #000000;
            flex: 1;
            .payNum {
                font-size: 44rpx;
                font-family: Source Han Sans, Source Han Sans;
                font-weight: 500;
                color: #ff9600;
            }
        }
        .payBtn {
            background-color: #fec433;
            color: #000;
            height: 80rpx;
            line-height: 80rpx;
            font-size: 28rpx;
            font-family: Source Han Sans, Source Han Sans;
            font-weight: 350;
            color: #000000;
            width: 350rpx;
            border-radius: 40rpx;
            border: none;
            box-shadow: none;
        }
    }
</style>
